import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import path, { resolve } from "path";
import { HttpsProxyAgent } from "https-proxy-agent";
import dotenv from "dotenv";
import fs from "fs";
// 先构造出.env*文件的绝对路径
const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = (relativePath: string) =>
  path.resolve(appDirectory, relativePath);
const pathsDotenv = resolveApp(".env");

// 按优先级由高到低的顺序加载.env文件
dotenv.config({ path: `${pathsDotenv}.local`, quiet: true });
dotenv.config({ path: `${pathsDotenv}.development.local`, quiet: true });
let httpsAgent = null;
if (globalThis.process.env.VITE_API_PROXY_URL) {
  globalThis.console.log(
    "use proxy:",
    globalThis.process.env.VITE_API_PROXY_URL
  );
  httpsAgent = new HttpsProxyAgent(globalThis.process.env.VITE_API_PROXY_URL);
}
// https://vite.dev/config/
export default defineConfig({
  base: "./",
  server: {
    host: "0.0.0.0",
    port: 8088,
    proxy: {
      "/api": {
        // agent: httpsAgent,
        // target: "https://guoyao.ctyun.cn:9443", // 测试
        target: "https://aichatapp.guoyaoyun.com:9443", // 生产
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, "/api"),
      },
      "/idp": {
        // target: "https://idptest.sinopharm.com", // 测试
        target: "https://auth.sinopharm.com", // 生产
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/idp/, "/idp"),
      },
      // "/oauth2": {
      //   agent: httpsAgent,
      //   target: "https://openapi.wps.cn",
      //   changeOrigin: true,
      //   rewrite: (path) => path.replace(/^\/oauth2/, "/oauth2"),
      // },
      // "/v7": {
      //   target: "https://openapi.wps.cn",
      //   changeOrigin: true,
      //   rewrite: (path) => path.replace(/^\/v7/, "/v7"),
      // },
    },
  },
  plugins: [vue()],
  resolve: {
    alias: {
      "@": resolve(__dirname, "src"),
      "@components": resolve(__dirname, "src/components"),
    },
  },
});
